import React, { useState, useEffect } from 'react';
import { 
    Card, 
    Button, 
    Table, 
    Space, 
    Avatar,
    Badge,
    Tag,
    message,
    Popconfirm,
    Input,
    Modal,
    Form,
    InputNumber,
    Progress
} from 'antd';
import { 
    SearchOutlined,
    StopOutlined,
    CheckCircleOutlined,
    UserOutlined,
    PlusOutlined
} from '@ant-design/icons';
import { fetchUserList, banUser, unbanUser, modifyUserPoints } from '../../store/modules/userStore';
import { useDispatch } from 'react-redux';

const { Search } = Input;
const { Item } = Form;

const AdminUserManagement = () => {
    const dispatch = useDispatch();
    const [form] = Form.useForm();
    const [users, setUsers] = useState([]);
    const [searchText, setSearchText] = useState('');
    const [loading, setLoading] = useState(false);
    const [pagination, setPagination] = useState({
        current: 1,
        pageSize: 10,
        total: 0
    });
    const [pointsModalVisible, setPointsModalVisible] = useState(false);
    const [currentUserId, setCurrentUserId] = useState(null);

    const roles = [
        { value: 'admin', label: '管理员' },
        { value: 'student', label: '学生' },
        { value: 'teacher', label: '教师' },
        { value: 'guest', label: '游客' }
    ];

    // 获取用户列表
    const fetchUsers = async (params = {}) => {
        setLoading(true);
        try {
            const { current: page, pageSize: size } = pagination;
            const res = await dispatch(fetchUserList({
                page,
                size,
                ...params
            }));
            
            if (res.code === 0) {
                const { total, list } = res.data;
                setUsers(list);
                setPagination({
                    ...pagination,
                    total
                });
            } else {
                message.error(res.msg || '获取用户列表失败');
            }
        } catch (error) {
            message.error('请求失败，请检查网络');
            console.error('获取用户列表错误:', error);
        } finally {
            setLoading(false);
        }
    };

    useEffect(() => {
        fetchUsers();
    }, [pagination.current, pagination.pageSize]);

    const handleTableChange = (pagination) => {
        setPagination(pagination);
    };

    // 封禁用户
    const handleBanUser = async (userId, username) => {
        try {
            const res = await dispatch(banUser(userId));
            
            if (res.code === 0) {
                message.success(res.data || '用户已封禁');
                fetchUsers(); // 刷新列表
            } else {
                message.warning(res.msg || '操作失败');
            }
        } catch (error) {
            message.error('封禁用户失败');
            console.error('封禁用户错误:', error);
        }
    };

    // 解封用户
    const handleUnbanUser = async (userId, username) => {
        try {
            const res = await dispatch(unbanUser(userId));
            
            if (res.code === 0) {
                message.success(res.data || '用户已解封');
                fetchUsers(); // 刷新列表
            } else {
                message.warning(res.msg || '操作失败');
            }
        } catch (error) {
            message.error('解封用户失败');
            console.error('解封用户错误:', error);
        }
    };

    // 打开积分修改模态框
    const showPointsModal = (userId) => {
        setCurrentUserId(userId);
        setPointsModalVisible(true);
        form.resetFields();
    };

    // 提交积分修改
    const handlePointsSubmit = async () => {
        try {
            const values = await form.validateFields();
            const res = await dispatch(modifyUserPoints({
                userId: currentUserId,
                points: values.points
            }));
            
            if (res.message) {
                message.success(res.message);
                setPointsModalVisible(false);
                fetchUsers(); // 刷新列表
            } else {
                message.error(res.error || '积分修改失败');
            }
        } catch (error) {
            console.error('积分修改错误:', error);
            message.error(error.error || '积分修改失败');
        }
    };

    const columns = [
        {
            title: '用户',
            dataIndex: 'username',
            key: 'username',
            render: (text, record) => (
                <Space>
                    <Avatar 
                        icon={<UserOutlined />} 
                        src={record.avatar}
                    />
                    <div>
                        <div>{text || '未设置'}</div>
                        <div style={{ fontSize: '12px', color: '#999' }}>
                            {record.email || '未设置邮箱'}
                        </div>
                    </div>
                </Space>
            ),
        },
        {
            title: '角色',
            dataIndex: 'role',
            key: 'role',
            render: (role) => {
                const roleInfo = roles.find(r => r.value === role);
                return (
                    <Tag color={
                        role === 'admin' ? 'red' : 
                        role === 'teacher' ? 'purple' : 'blue'
                    }>
                        {roleInfo?.label || role}
                    </Tag>
                );
            }
        },
        {
            title: '等级',
            dataIndex: 'level',
            key: 'level',
            sorter: (a, b) => a.level - b.level,
        },
        {
            title: '积分',
            dataIndex: 'seedPoints',
            key: 'seedPoints',
            render: (points) => points.toLocaleString()
        },
        {
    title: '分享率',
    dataIndex: 'sharingRate',
    key: 'sharingRate',
    render: (rate) => {
      // 格式化分享率为2位小数
      const formattedRate = parseFloat(rate).toFixed(2);
      // 根据分享率值显示不同颜色
      let color = '#108ee9'; // 默认蓝色
      if (rate < 0.5) color = '#f5222d'; // 低于0.5显示红色
      else if (rate >= 1.0) color = '#52c41a'; // 大于等于1.0显示绿色
      
      return (
        <Tag color={color}>
          {formattedRate}
        </Tag>
      );
    },
    sorter: (a, b) => a.sharingRate - b.sharingRate,
  },
   {
        title: '不活跃天数',
        dataIndex: 'unactivateDay',
        key: 'unactivateDay',
        render: (days) => (
            <Tag color={days >= 7 ? 'red' : days >= 5 ? 'orange' : 'blue'}>
                {days}天{days >= 7 && ' (需封号)'}
            </Tag>
        ),
        sorter: (a, b) => a.unactivateDay - b.unactivateDay,
    },
    {
        title: '考核剩余天数',
        dataIndex: 'assessDay',
        key: 'assessDay',
        render: (days) => (
            <Tag color={days <= 7 ? 'red' : days <= 15 ? 'orange' : 'green'}>
                {days}天
            </Tag>
        ),
        sorter: (a, b) => a.assessDay - b.assessDay,
    },
    {
        title: '考核上传量',
        dataIndex: 'uploadAssess',
        key: 'uploadAssess',
        render: (bytes) => {
            const formattedSize = formatSize(bytes);
            const requiredSize = formatSize(30 * 1024 * 1024 * 1024); // 30GB
            const progress = Math.min(100, (bytes / (30 * 1024 * 1024 * 1024)) * 100).toFixed(2);
            
            return (
                <div>
                    <div style={{ marginBottom: 4 }}>
                        {formattedSize} / {requiredSize}
                    </div>
                    <Progress 
                        percent={progress} 
                        status={progress >= 100 ? 'success' : 'active'}
                        strokeColor={progress >= 100 ? '#52c41a' : '#1890ff'}
                        size="small" 
                    />
                </div>
            );
        },
        sorter: (a, b) => a.uploadAssess - b.uploadAssess,
    },
        {
            title: '状态',
            dataIndex: 'baned',
            key: 'baned',
            render: (baned) => (
                <Badge 
                    status={baned ? 'error' : 'success'} 
                    text={baned ? '已封禁' : '正常'}
                />
            )
        },
        {
            title: '操作',
            key: 'action',
            render: (_, record) => (
                <Space size="middle">
                    <Button 
                        type="primary" 
                        icon={<PlusOutlined />}
                        size="small"
                        onClick={() => showPointsModal(record.userId)}
                    >
                        修改积分
                    </Button>
                    
                    {record.baned ? (
                        <Popconfirm
                            title={`确定要解封用户 ${record.username || '该用户'} 吗?`}
                            onConfirm={() => handleUnbanUser(record.userId, record.username)}
                            okText="确定"
                            cancelText="取消"
                        >
                            <Button 
                                type="primary" 
                                icon={<CheckCircleOutlined />}
                                size="small"
                            >
                                解封
                            </Button>
                        </Popconfirm>
                    ) : (
                        <Popconfirm
                            title={`确定要封禁用户 ${record.username || '该用户'} 吗?`}
                            onConfirm={() => handleBanUser(record.userId, record.username)}
                            okText="确定"
                            cancelText="取消"
                        >
                            <Button 
                                danger 
                                icon={<StopOutlined />}
                                size="small"
                            >
                                封禁
                            </Button>
                        </Popconfirm>
                    )}
                </Space>
            ),
        },
    ];

    const formatSize = (bytes) => {
        if (bytes === 0) return '0 Bytes';
        const k = 1024;
        const sizes = ['Bytes', 'KB', 'MB', 'GB', 'TB'];
        const i = Math.floor(Math.log(bytes) / Math.log(k));
        return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i];
    };

    return (
        <div className="admin-user-management">
            <Card
                title="用户管理"
                extra={
                    <Search
                        placeholder="搜索用户名或邮箱"
                        allowClear
                        enterButton={<SearchOutlined />}
                        size="middle"
                        style={{ width: 250 }}
                        onSearch={value => {
                            setSearchText(value);
                            fetchUsers({ keyword: value });
                        }}
                        onChange={e => setSearchText(e.target.value)}
                    />
                }
            >
                <Table 
                    columns={columns} 
                    dataSource={users} 
                    rowKey="userId"
                    bordered
                    loading={loading}
                    pagination={{
                        ...pagination,
                        showSizeChanger: true,
                        showQuickJumper: true,
                        showTotal: total => `共 ${total} 条`,
                        pageSizeOptions: ['10', '20', '50', '100']
                    }}
                    onChange={handleTableChange}
                />
            </Card>

            {/* 积分修改模态框 */}
            <Modal
                title="修改用户积分"
                visible={pointsModalVisible}
                onOk={handlePointsSubmit}
                onCancel={() => setPointsModalVisible(false)}
                okText="确认"
                cancelText="取消"
            >
                <Form form={form} layout="vertical">
                    <Item
                        name="points"
                        label="积分数量"
                        rules={[
                            { required: true, message: '请输入积分数量' },
                            { type: 'number', min: 1, message: '积分必须大于0' }
                        ]}
                    >
                        <InputNumber 
                            style={{ width: '100%' }} 
                            placeholder="请输入要增加的积分数量" 
                        />
                    </Item>
                </Form>
            </Modal>
        </div>
    );
};

export default AdminUserManagement;